home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 3104 < prev    next >
Encoding:
Text File  |  1996-08-06  |  1.7 KB  |  57 lines

  1. Path: news.primenet.com!not-for-mail
  2. From: gbe@primenet.com (Gary Edstrom)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: [Q] new-allocated objects within try block
  5. Date: 20 Jan 1996 15:51:01 -0700
  6. Organization: Sequoia Software
  7. Sender: root@primenet.com
  8. Message-ID: <31016b0a.148193273@news.primenet.com>
  9. References: <monnet-2001962147210001@alpnet76.alpes-net.fr>
  10. X-Posted-By: ip059.lax.primenet.com
  11. X-Newsreader: Forte Agent .99c/16.141
  12.  
  13. Here is a way of handling your problem using an intermediate helper
  14. class.  With this approach, you don't need to worry about executing
  15. the new/delete operators.
  16.  
  17. class ABC { public: virtual void DoSomething() = 0; };
  18. class A : public ABC { public: virtual void DoSomething(); };
  19. class B : public ABC { public: virtual void DoSomething(); };
  20.  
  21. class Q
  22.     {
  23.     private:
  24.         ABC * ptr;
  25.     public:
  26.         void DoSomething() { ptr->DoSomething(); }
  27.  
  28.         Q(test) { if (test) ptr = new A; else ptr = new B; }
  29.         ~Q() { delete ptr; }
  30.     };
  31.  
  32. Now, here is your modified try/catch block:
  33.  
  34. try {
  35.     Q p(test);
  36.     ...
  37.     throw sthg;
  38.     ...
  39.     p.DoSomething();
  40.     } 
  41. catch (...) { ... }
  42.  
  43. Using this approach, the destructor for Q will be executed
  44. automatically after the program hits the "throw" statement.  Also
  45. notice that the arrow notation has been changed to a dot notation.  To
  46. as great a degree as possible, I try to follow the convention of only
  47. using "new" operators inside constructors and "delete" operators
  48. inside destructors.
  49.  
  50. Gary Edstrom <gbe@primenet.com>
  51.  
  52. --
  53. Gary Edstrom <gbe@primenet.com> | Sequoia Software
  54. PO Box 9573                     | Programming & Technical Services
  55. Glendale CA 91226-0573          | PGP Key ID: 0x1A0D44BD
  56. PGP Fingerprint: 72 AA 4F 73 05 53 89 C6  8A EE F4 EE D1 C0 13 8D 
  57.